import React, { Component } from 'react'
import { Modal, message, notification } from 'antd'
import { SmileOutlined } from '@ant-design/icons';
import QueryList from '@/components/basicWidget/QueryList'
import InputWidget from '@/components/basicWidget/InputWidget';
import Button from '@/components/basicWidget/Button';
import formValidate from '@/service/validate/formValidate';
import { createDocument, deleteDocumentById } from '@/service/document/documentService';
import secrecy from '@/service/secrecy/secrecyService';
import { Link } from 'react-router-dom';


/**
 * 个人保险柜
 * @author liu_jshan
 * 20240714
 * @version 1.0
 */
class PersonalSafeBox extends Component {

    constructor(props) {
        super(props)
        this.state = {
            addModalProps: {
                modalVisual: false
            },
            addModalKey: new Date().getTime() + '',
            selectedRowKeys: [],
            selectedRows: []
        }
    }

    onSelectChange = async (selectedRowKeys, selectedRows) => {
        this.setState({
            selectedRowKeys,
            selectedRows
        })
    }

    addModalOpen = async () => {
        await new Promise(resolve => {
            this.setState(preState => {
                return {
                    addModalProps: {
                        ...preState.addModalProps,
                        modalVisual: true,
                    },
                    addModalKey: new Date().getTime() + '',
                    insuranceName: '',
                    insuranceDesc: '',
                    insuranceContent: ''
                }
            }, resolve)
        })
    }

    addModalCancel = async () => {
        await new Promise(resolve => {
            this.setState(preState => {
                return {
                    addModalProps: {
                        ...preState.addModalProps,
                        modalVisual: false
                    }
                }
            }, resolve)
        })
    }

    actionColumns = (columns, data) => {
        data = data.map(item => {
            const content = item.insuranceContent
            item.insuranceContent = (
                <Link onClick={() => {
                    notification.open({
                        message: item.insuranceName,
                        placement: 'top',
                        description: secrecy.AES_Decrypt(content),
                        icon: <SmileOutlined style={{ color: '#108ee9' }} />,
                        duration: 5
                    })
                }}>查看</Link>
            )
            return item
        })
        return { newColumns: columns, newData: data }
    }

    //输入框变化获取值(通过value)
    onChange = (inputName) => {
        return async (value) => {
            await new Promise((resolve) => {
                this.setState({ [inputName]: value }, resolve)
            })
        }
    }

    renderAddModal = () => {
        return (
            <Modal
                title='新增保险信息'
                open={this.state.addModalProps.modalVisual}
                onCancel={this.addModalCancel}
                footer={null}
            >
                <div
                    key={this.state.addModalKey}
                    style={{ margin: '1em', display: 'flex', flexDirection: 'column' }}>
                    <InputWidget
                        style={{ marginBottom: '1em' }}
                        prefixName={{ content: '名称' }}
                        value={this.state.insuranceName}
                        onChange={this.onChange('insuranceName')}
                        rules={
                            [
                                {
                                    validate: formValidate.getValidater('isMust'),
                                    failMessage: '名称不能为空'
                                }
                            ]
                        }
                        ref={ref => { this.insuranceNameI = ref }}
                    >
                    </InputWidget>
                    <InputWidget
                        style={{ marginBottom: '1em' }}
                        prefixName={{ content: '描述' }}
                        value={this.state.insuranceDesc}
                        onChange={this.onChange('insuranceDesc')}
                        rules={
                            [
                                {
                                    validate: formValidate.getValidater('isMust'),
                                    failMessage: '描述不能为空'
                                }
                            ]
                        }
                        ref={ref => { this.insuranceDescI = ref }}
                    >
                    </InputWidget>
                    <InputWidget
                        style={{ marginBottom: '1em' }}
                        prefixName={{ content: '内容' }}
                        value={this.state.insuranceContent}
                        onChange={this.onChange('insuranceContent')}
                        rules={
                            [
                                {
                                    validate: formValidate.getValidater('isMust'),
                                    failMessage: '内容不能为空'
                                }
                            ]
                        }
                        ref={ref => { this.insuranceContentI = ref }}
                    >
                    </InputWidget>
                    <Button
                        onClick={async () => {
                            const { insuranceNameI, insuranceDescI, insuranceContentI } = this
                            let refArray = [insuranceNameI, insuranceDescI, insuranceContentI]
                            const validateResult = await formValidate.validateForm(refArray)
                            if (validateResult === false) return false
                            const { insuranceName, insuranceDesc, insuranceContent } = this.state
                            const response = await createDocument({
                                serviceName: 'blog',
                                collectionName: 'user_insurance_info',
                                content: {
                                    insuranceName,
                                    insuranceDesc,
                                    insuranceContent: secrecy.AES_Encrypt(insuranceContent),
                                    customerId: this.props.user.id
                                }
                            })
                            if (response) {
                                if (response.code === 200) {
                                    message.success('操作成功')
                                    await this.addModalCancel()
                                    await this.queryList.onQuery()
                                } else {
                                    message.warning(response.message)
                                }
                            }
                        }}
                    >保存</Button>
                </div>
            </Modal>
        )
    }

    render() {
        return (
            <>
                <QueryList
                    queryCode='personalSafeBox'
                    actionColumns={this.actionColumns}
                    addModalOpen={this.addModalOpen}
                    onDelete={async () => {
                        if (this.state.selectedRowKeys.length === 0) {
                            message.warning('请选择要删除的数据！')
                            return false
                        }
                        const response = await deleteDocumentById({
                            id: this.state.selectedRowKeys[0],
                            serviceName: 'customer',
                            collectionName: 'user_insurance_info'
                        })
                        if (response && response.code === 200) {
                            message.success('删除成功')
                            await this.queryList.onQuery()
                        }
                    }}
                    onSelectChange={this.onSelectChange}
                    refData={{
                        customerId: this.props.user.id
                    }}
                    ref={queryList => this.queryList = queryList}
                >
                </QueryList>
                {this.renderAddModal()}
            </>
        )
    }
}

export default PersonalSafeBox
